<?php
require($_SERVER['DOCUMENT_ROOT'] . '/setting.php');
function verifyToken($token)
{
    global $redis_pz;
    $redis = new Redis();
    $redis->connect($redis_pz['host'], $redis_pz['port']);
    $redis->auth($redis_pz['password']);
    $data = $redis->get($token);
    if ($data) {
        $data = json_decode($data, true);
        if ($data['timestamp'] > time()) {
            return true;
        }
    }
    return false;
}
function gbToMb($gb) {
    $mb = $gb * 1024;
    return $mb;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'error: requests are not allowed']);
    exit;
}
require($_SERVER['DOCUMENT_ROOT'] . '/cofd/functions.php');
$data_y = file_get_contents("php://input");
$data_x = json_decode($data_y, true);
$token  = $data_x['token'];
if ($token != '') {
    $token  = encrypt($token, 'D', 'yhsdylpo9342');
} else {
    echo json_encode(['success' => false, 'message' => 'error: invalid token']);
    exit;
}
if (!verifyToken($token)) {
    echo json_encode(['success' => false, 'message' => 'error: invalid token']);
    exit;
}
$type = $data_x['types'];
require($_SERVER['DOCUMENT_ROOT'] . '/cofd/common.php');
$user_id = $data_x['userid'];
if ($type == 'user') {
    $sql = "SELECT bdmail,capacity,rate,rated,capacityed FROM `user` WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $user_id);
    if ($stmt->execute()) {
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            echo json_encode(['success' => true, 'message' => 'success', 'data' => $row]);
        } else {
            echo json_encode(['success' => false, 'message' => 'error: user not found']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'error: database error']);
    }
} elseif ($type == 'file') {
    $file_id = (string)encrypt($data_x['fileid'], 'D', 'yhsdylpo9342');
    $sql = "SELECT names,pwd,timei,asets,numd,sizes FROM `files` WHERE id = ? AND froms = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ss', $file_id, $user_id);
    if ($stmt->execute()) {
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            if ($row = $result->fetch_assoc()) {
                $row['sizes'] = gbToMb($row['sizes']);
                echo json_encode(['success' => true, 'message' => 'success', 'data' => $row]);
            } else {
                echo json_encode(['success' => false, 'message' => 'error: file not found']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'error: file not found']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'error: database error']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'error: invalid type']);
    exit;
}
$stmt->close();
$conn->close();
